package local.blueheart.data.springdatademo.domino;

import local.blueheart.data.springdatademo.exception.DominoException;
import local.blueheart.data.springdatademo.exception.DominoExceptionEnum;
import lotus.domino.Database;
import lotus.domino.NotesException;
import lotus.domino.NotesFactory;
import lotus.domino.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DSession extends DBase {

    private static final Logger LOGGER = LoggerFactory.getLogger(DSession.class);

    /**
     * 保存Session到Base
     * @param session
     */
    private DSession(Session session){
        super(session);
    }

    public static DSession sessionFactory(String serverAddress,String username,String password) throws DominoException {
        try {
            Session session = NotesFactory.createSession(serverAddress, username, password);
            DSession dSession = new DSession(session);
            return dSession;
        }catch (NotesException ne){
            LOGGER.error("Session创建出错",ne);
            throw new DominoException(ne, DominoExceptionEnum.GET_SESSION_ERR);
        }
    }

    /**
     * 返回一个DDatabase
     * @param serverPath
     * @param dbPath
     * @return
     * @throws NotesException
     */
    public DDatabase getDatabase(String serverPath,String dbPath) throws DominoException {
        try{
            Session session = (Session) getBase();
            Database database = session.getDatabase(serverPath, dbPath);
            if (database.isOpen()) {
                DDatabase dDatabase = new DDatabase(database);
                addChild(dDatabase);
                return dDatabase;

            } else {
                LOGGER.error("数据库获取失败 {} {}", serverPath, dbPath);
                return null;
            }
        }catch (NotesException ne){
            LOGGER.error("获取Db出错",ne);
            throw new DominoException(ne,DominoExceptionEnum.GET_DB_ERR);
        }

    }

}
